package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.entity.MaintenanceReminder;
import com.vehiclemanagement.service.MaintenanceReminderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 车辆维修保养提醒控制器
 */
@RestController
@RequestMapping("/api/maintenance/reminder")
@Slf4j
public class MaintenanceReminderController {

    @Autowired
    private MaintenanceReminderService maintenanceReminderService;

    /**
     * 分页查询维修保养提醒
     */
    @GetMapping("/list")
    public Result<IPage<MaintenanceReminder>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Integer reminderType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {

        log.info("分页查询维修保养提醒: current={}, size={}, searchTerm={}, vehicleId={}, reminderType={}, status={}, startTime={}, endTime={}",
                current, size, searchTerm, vehicleId, reminderType, status, startTime, endTime);

        try {
            IPage<MaintenanceReminder> page = maintenanceReminderService.pageMaintenanceReminders(
                    current, size, searchTerm, vehicleId, reminderType, status, startTime, endTime);
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询维修保养提醒失败", e);
            return Result.error("获取维修保养提醒列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取维修保养提醒详情
     */
    @GetMapping("/{id}")
    public Result<MaintenanceReminder> getById(@PathVariable Long id) {
        log.info("获取维修保养提醒详情: id={}", id);

        try {
            MaintenanceReminder reminder = maintenanceReminderService.getMaintenanceReminderById(id);
            if (reminder == null) {
                return Result.error("找不到指定的维修保养提醒");
            }
            return Result.success(reminder);
        } catch (Exception e) {
            log.error("获取维修保养提醒详情失败", e);
            return Result.error("获取维修保养提醒详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加维修保养提醒
     */
    @PostMapping
    public Result<Boolean> add(@RequestBody MaintenanceReminder reminder) {
        log.info("添加维修保养提醒: {}", reminder);

        // 校验必填字段
        if (reminder.getVehicleId() == null) {
            return Result.validateFailed("车辆ID不能为空");
        }
        if (reminder.getReminderType() == null) {
            return Result.validateFailed("提醒类型不能为空");
        }
        if (reminder.getReminderContent() == null || reminder.getReminderContent().trim().isEmpty()) {
            return Result.validateFailed("提醒内容不能为空");
        }
        if ("mileage".equals(reminder.getFrequency()) && reminder.getMileageThreshold() == null) {
            return Result.validateFailed("按里程提醒时，里程阈值不能为空");
        }
        if (!"mileage".equals(reminder.getFrequency()) && reminder.getReminderDate() == null) {
            return Result.validateFailed("非里程提醒时，提醒日期不能为空");
        }

        try {
            boolean success = maintenanceReminderService.addMaintenanceReminder(reminder);
            return success ? Result.success("添加维修保养提醒成功", true) : Result.error("添加维修保养提醒失败");
        } catch (Exception e) {
            log.error("添加维修保养提醒失败", e);
            return Result.error("添加维修保养提醒失败：" + e.getMessage());
        }
    }

    /**
     * 更新维修保养提醒
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody MaintenanceReminder reminder) {
        log.info("更新维修保养提醒: {}", reminder);

        if (reminder.getId() == null) {
            return Result.validateFailed("维修保养提醒ID不能为空");
        }

        try {
            boolean success = maintenanceReminderService.updateMaintenanceReminder(reminder);
            return success ? Result.success("更新维修保养提醒成功", true) : Result.error("更新维修保养提醒失败");
        } catch (Exception e) {
            log.error("更新维修保养提醒失败", e);
            return Result.error("更新维修保养提醒失败：" + e.getMessage());
        }
    }

    /**
     * 删除维修保养提醒
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        log.info("删除维修保养提醒: id={}", id);

        try {
            boolean success = maintenanceReminderService.deleteMaintenanceReminder(id);
            return success ? Result.success("删除维修保养提醒成功", true) : Result.error("删除维修保养提醒失败");
        } catch (Exception e) {
            log.error("删除维修保养提醒失败", e);
            return Result.error("删除维修保养提醒失败：" + e.getMessage());
        }
    }

    /**
     * 处理提醒
     */
    @PutMapping("/process/{id}")
    public Result<Boolean> processReminder(
            @PathVariable Long id,
            @RequestParam Integer status,
            @RequestParam(required = false) String remark) {

        log.info("处理维修保养提醒: id={}, status={}, remark={}", id, status, remark);

        if (status != 1 && status != 2) {
            return Result.validateFailed("状态值无效，只能是1（已处理）或2（已忽略）");
        }

        try {
            boolean success = maintenanceReminderService.processReminder(id, status, remark);
            return success ? Result.success("处理维修保养提醒成功", true) : Result.error("处理维修保养提醒失败");
        } catch (Exception e) {
            log.error("处理维修保养提醒失败", e);
            return Result.error("处理维修保养提醒失败：" + e.getMessage());
        }
    }

    /**
     * 获取待处理提醒数量
     */
    @GetMapping("/count")
    public Result<Integer> countPendingReminders() {
        log.info("获取待处理维修保养提醒数量");

        try {
            int count = maintenanceReminderService.countPendingReminders();
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取待处理维修保养提醒数量失败", e);
            return Result.error("获取待处理维修保养提醒数量失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定车辆的提醒列表
     */
    @GetMapping("/vehicle/{vehicleId}")
    public Result<List<MaintenanceReminder>> getByVehicleId(@PathVariable Long vehicleId) {
        log.info("获取车辆维修保养提醒列表: vehicleId={}", vehicleId);

        try {
            List<MaintenanceReminder> reminders = maintenanceReminderService.getMaintenanceRemindersByVehicleId(vehicleId);
            return Result.success(reminders);
        } catch (Exception e) {
            log.error("获取车辆维修保养提醒列表失败", e);
            return Result.error("获取车辆维修保养提醒列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取即将到期的提醒列表
     */
    @GetMapping("/upcoming")
    public Result<List<MaintenanceReminder>> getUpcomingReminders(
            @RequestParam(defaultValue = "7") Integer days) {

        log.info("获取即将到期的维修保养提醒列表: days={}", days);

        try {
            List<MaintenanceReminder> reminders = maintenanceReminderService.getUpcomingReminders(days);
            return Result.success(reminders);
        } catch (Exception e) {
            log.error("获取即将到期的维修保养提醒列表失败", e);
            return Result.error("获取即将到期的维修保养提醒列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取已超期的提醒列表
     */
    @GetMapping("/overdue")
    public Result<List<MaintenanceReminder>> getOverdueReminders() {
        log.info("获取已超期的维修保养提醒列表");

        try {
            List<MaintenanceReminder> reminders = maintenanceReminderService.getOverdueReminders();
            return Result.success(reminders);
        } catch (Exception e) {
            log.error("获取已超期的维修保养提醒列表失败", e);
            return Result.error("获取已超期的维修保养提醒列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取需要按里程提醒的车辆
     */
    @GetMapping("/mileage-threshold")
    public Result<List<Map<String, Object>>> getVehiclesExceedingMileageThreshold() {
        log.info("获取需要按里程提醒的车辆");

        try {
            List<Map<String, Object>> vehicles = maintenanceReminderService.getVehiclesExceedingMileageThreshold();
            return Result.success(vehicles);
        } catch (Exception e) {
            log.error("获取需要按里程提醒的车辆失败", e);
            return Result.error("获取需要按里程提醒的车辆失败：" + e.getMessage());
        }
    }

    /**
     * 按提醒类型统计
     */
    @GetMapping("/statistics/type")
    public Result<List<Map<String, Object>>> countRemindersByType() {
        log.info("按提醒类型统计维修保养提醒");

        try {
            List<Map<String, Object>> statistics = maintenanceReminderService.countRemindersByType();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("按提醒类型统计维修保养提醒失败", e);
            return Result.error("按提醒类型统计维修保养提醒失败：" + e.getMessage());
        }
    }
} 